package com.fancon.android.gardenjokesx.social;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import twitter4j.IDs;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.http.AccessToken;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.fancon.android.gardenjokesx.entity.FacebookUser;
import com.fancon.android.gardenjokesx.entity.Place;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.StringUtil;

public class SocialUntil {
	private Context mContext;

	private Twitter mTwitter = null;
	private AccessToken mTwitterAccessToken = null;

	public SocialUntil(Context context) {
		mContext = context;

	}

	// TWITTER

	@SuppressWarnings("deprecation")
	private void configureToken() {
		if (mTwitterAccessToken != null) {
			mTwitter.setOAuthConsumer(Keys.TWITTER_CONSUMER_KEY,
					Keys.TWITTER_CONSUMER_SECRET);

			mTwitter.setOAuthAccessToken(mTwitterAccessToken);
		}
	}

	/**
	 * Post image + status to Twitter
	 * 
	 * @param file
	 *            : URL cua image hoac dia chi luu trong Sdcard (vi du:
	 *            /mnt/sdcard/temp/SBAD.jpg)
	 * @param status
	 *            : chuoi String post len blog twitter
	 * @param twitterToken
	 *            : Token lay trong DB
	 * @param twitterSecret
	 *            : TokenSecret lay trong DB
	 * @return
	 */
	public boolean postToTwitter(String file, String status,
			String twitterToken, String twitterSecret) {
		if (mTwitterAccessToken == null) {
			mTwitter = new TwitterFactory().getInstance();
			mTwitterAccessToken = new AccessToken(twitterToken, twitterSecret);
			configureToken();
		}
		// Configuration conf = new ConfigurationBuilder()
		// .setOAuthConsumerKey(Keys.TWITTER_CONSUMER_KEY)
		// .setOAuthConsumerSecret(Keys.TWITTER_CONSUMER_SECRET)
		// .setOAuthAccessToken(twitterToken)
		// .setOAuthAccessTokenSecret(twitterSecret)
		// .build();
		//
		// OAuthAuthorization auth = new OAuthAuthorization(conf,
		// conf.getOAuthConsumerKey(), conf.getOAuthConsumerSecret(),
		// new AccessToken(conf.getOAuthAccessToken(),
		// conf.getOAuthAccessTokenSecret()));
		//
		// ImageUpload upload = ImageUpload.getTwitpicUploader(
		// Keys.TWITPIC_API_KEY, auth);
		//
		// Log.v("Start sending ...","");

		try {
			// Up image len Twitpic va up status len blog cua Twitter
			String imageUrl;
			if (file.startsWith("http") || file.length() == 0) {
				imageUrl = file;
				String statusUrl = status + " " + imageUrl;
				updateStatus(statusUrl);
			} else {
				// /mnt/sdcard/temp/SBAD.jpg
				// imageUrl = upload.upload(new File(file));
				updateStatus(status);
			}

			// Log.v("Post to Twitter","Twitpic: " + imageUrl);
			mTwitterAccessToken = null;
			mTwitter = null;
			return true;
		} catch (Exception e) {
			Log.v("Failed to send", e.getMessage());
			mTwitter = null;
			mTwitterAccessToken = null;
			return false;
		}
	};

	/**
	 * Lay ve chuoi String luu list FriendIDs
	 * 
	 * @param twitterToken
	 *            : lay trong DB
	 * @param twitterSecret
	 *            : lay trong DB
	 * @return
	 */
	public String getFriendIdsTwitter(String twitterToken, String twitterSecret) {
		if (mTwitterAccessToken == null) {
			mTwitter = new TwitterFactory().getInstance();
			mTwitterAccessToken = new AccessToken(twitterToken, twitterSecret);
			configureToken();
		}

		String listFriendIDs = "";
		try {
			User user = mTwitter.verifyCredentials();
			String[] args = new String[1];
			args[0] = user.getName();
			//args[0] = String.valueOf(user.getId());
			long cursor = -1;
			IDs ids;
			do {
				if (0 < args.length) {
					ids = mTwitter.getFriendsIDs(args[0], cursor);
				} else {
					ids = mTwitter.getFriendsIDs(cursor);
				}

				for (int i = 0; i < ids.getIDs().length; i++) {
					listFriendIDs = listFriendIDs
							+ Integer.toString(ids.getIDs()[i]) + ",";
					Log.d("username", mTwitter.showUser(ids.getIDs()[i])
							.getName());
				}
			} while ((cursor = ids.getNextCursor()) != 0);
		} catch (TwitterException te) {
			te.printStackTrace();
			Log.v("Failed to get friends' ids: ", te.getMessage());
		}

		Log.v("list FriendIDs", listFriendIDs);
		mTwitterAccessToken = null;
		mTwitter = null;
		return listFriendIDs;
	}

	/**
	 * Update status len Twitter
	 * 
	 * @param status
	 * @throws Exception
	 */
	public void updateStatus(String status) throws Exception {
		try {
			mTwitter.updateStatus(status);
		} catch (TwitterException e) {
			Log.v("Update status false", e.getMessage());
			throw e;
		}
	}

	/**
	 * Lay ImageProfile cua User, tra ve la URL
	 * 
	 * @param twitterToken
	 *            : lay trong DB
	 * @param twitterSecret
	 *            : lay trong DB
	 * @return
	 */
	public String getImageProfile(String twitterToken, String twitterSecret) {
		String imageProfileUrl = "";

		if (mTwitterAccessToken == null) {
			mTwitter = new TwitterFactory().getInstance();
			mTwitterAccessToken = new AccessToken(twitterToken, twitterSecret);
			configureToken();
		}

		User user;
		URL url = null;
		try {
			user = mTwitter.showUser(mTwitter.getId());
			url = user.getProfileImageURL();

			imageProfileUrl = url.getProtocol() + "://" + url.getHost()
					+ (url.getPath() == null ? "" : url.getPath())
					+ (url.getQuery() == null ? "" : "?" + url.getQuery());
			// if (imageProfileUrl.length()>0) {
			// Log.d("URL Profile", imageProfileUrl);
			// imageProfileUrl = imageProfileUrl.replace("_normal.",
			// "_bigger.");
			// Log.d("URL Profile", imageProfileUrl);
			// }
			// @binhbt comment tmp
			// ImageLoader imageLoader = ((IMeshCache)mContext).getmImgLoader();
			// imageProfileUrl = imageLoader.getImageFromSD(imageProfileUrl);

			// imageLoader = null;

		} catch (IllegalStateException e) {
			imageProfileUrl = null;
			e.printStackTrace();
		} catch (TwitterException e) {
			imageProfileUrl = null;
			e.printStackTrace();
		}

		mTwitterAccessToken = null;
		mTwitter = null;
		return imageProfileUrl;
	}

	/**
	 * Get Twitter ID
	 * 
	 * @param twitterToken
	 * @param twitterSecret
	 * @return
	 */
	public int getTwitterID(String twitterToken, String twitterSecret) {
		int twitterID = 0;
		if (mTwitterAccessToken == null) {
			mTwitter = new TwitterFactory().getInstance();
			mTwitterAccessToken = new AccessToken(twitterToken, twitterSecret);
			configureToken();
		}
		try {
			twitterID = mTwitter.getId();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (TwitterException e) {
			e.printStackTrace();
		}

		mTwitterAccessToken = null;
		mTwitter = null;
		return twitterID;
	}

	// FACEBOOK

	/**
	 * Lay listFriendID cua Facebook
	 * 
	 * @param accessToken
	 *            : lay trong DB Co the test bang Token:
	 *            AAADHCqX42ukBAIbS1N4oHNOMhpZAYbyoHAihFR7oHIAZBYOpt5ME4dBI3sim6S4i99xYV4bqvZCRDEF3np9UiDG5JPNOlhWj6vTxvHhGwZDZD
	 * @return
	 */
	public ArrayList<FacebookUser> getFriendIdsFacebook(String accessToken) {
		ArrayList<FacebookUser> listFBUser = new ArrayList<FacebookUser>();

		Utility.mFacebook = new Facebook(Keys.APP_ID);
		Utility.mFacebook.setAccessToken(accessToken);
		Utility.mFacebook.setAccessExpires(0);

		String query = "select name, current_location, uid, pic_square, first_name, middle_name, last_name from user where uid in (select uid2 from friend where uid1=me()) order by name";
		Bundle params = new Bundle();
		params.putString("method", "fql.query");
		params.putString("query", query);

		try {
			String response = Utility.mFacebook.request(null, params, "GET");
			JSONArray jsonArrayFB = new JSONArray(response);

			for (int i = 0; i < jsonArrayFB.length(); i++) {
				FacebookUser fbUser = new FacebookUser();
				fbUser.setFacebookId(jsonArrayFB.getJSONObject(i).getString(
						"uid"));
				fbUser.setUsername(jsonArrayFB.getJSONObject(i).getString(
						"name"));
				fbUser.setImageprofile(jsonArrayFB.getJSONObject(i).getString(
						"pic_square"));
				fbUser.setfirstNameFB(jsonArrayFB.getJSONObject(i).getString(
						"first_name"));
				fbUser.setmiddleNameFB(jsonArrayFB.getJSONObject(i).getString(
						"middle_name"));
				fbUser.setlastNameFB(jsonArrayFB.getJSONObject(i).getString(
						"last_name"));

				listFBUser.add(fbUser);
			}

			jsonArrayFB = null;
		} catch (FileNotFoundException e) {
			listFBUser = null;
			Log.e("FileNotFoundException", e.getMessage());
		} catch (MalformedURLException e) {
			listFBUser = null;
			Log.e("MalformedURLException", e.getMessage());
		} catch (IOException e) {
			listFBUser = null;
			Log.e("IOException", e.getMessage());
		} catch (JSONException e) {
			listFBUser = null;
			Log.e("JSONException", e.getMessage());
		}

		Utility.mFacebook = null;
		return listFBUser;
	}

	/**
	 * Lay userInfo cua account Tra ve chuoi string co dang: name,id,url_profile
	 * 
	 * @param accessToken
	 * @return
	 */
	public com.fancon.android.gardenjokesx.entity.User userInfoFB(
			String accessToken) {
		com.fancon.android.gardenjokesx.entity.User user = new com.fancon.android.gardenjokesx.entity.User();

		Utility.mFacebook = new Facebook(Keys.APP_ID);
		Utility.mFacebook.setAccessToken(accessToken);
		Utility.mFacebook.setAccessExpires(0);

		Bundle params = new Bundle();
		params.putString(
				"fields",
				"id, name, first_name, last_name, gender, username, birthday, email, interested_in, location");

		try {
			String resp = Utility.mFacebook.request("me", params, "GET");

			JsonPaser jP = new JsonPaser();
			user = jP.getUserProfileFacebook(resp);

			if (user.getLocation_idFB() != null
					&& user.getLocation_idFB().length() > 0) {
				JSONObject jOb = null;

				URL url = new URL("https://graph.facebook.com/"
						+ user.getLocation_idFB());
				String location = getJSON(url);
				if (location != null && location.length() > 0) {
					jOb = new JSONObject(location);
					if (jOb.opt("location") != null) {
						if (jOb.getJSONObject("location").opt("latitude") != null) {
							user.setLatitude(jOb.getJSONObject("location")
									.getDouble("latitude"));
						}
						if (jOb.getJSONObject("location").opt("longitude") != null) {
							user.setLongitude(jOb.getJSONObject("location")
									.getDouble("longitude"));
						}

						URL url2 = new URL(
								"http://maps.googleapis.com/maps/api/geocode/json?latlng="
										+ user.getLatitude() + ","
										+ user.getLongitude() + "&sensor=false");

						String locat = getJSON(url2);
						if (locat != null && locat.length() > 0) {
							jOb = null;
							jOb = new JSONObject(locat);
							JSONArray inter = jOb.getJSONArray("results");
							if (inter != null && inter.length() > 0) {
								JSONArray address = inter.getJSONObject(
										inter.length() - 1).getJSONArray(
										"address_components");
								if (address.getJSONObject(address.length() - 1)
										.opt("long_name") != null) {
									user.setCurrent_country(address
											.getJSONObject(address.length() - 1)
											.getString("long_name"));
									Log.d("Country", user.getCurrent_country());
								}
							}
						}
					}
				}
			}

			jP = null;
		} catch (FileNotFoundException e) {
			Log.e("FileNotFoundException", e.getMessage());
			user = null;
		} catch (MalformedURLException e) {
			Log.e("MalformedURLException", e.getMessage());
			user = null;
		} catch (IOException e) {
			Log.e("IOException", e.getMessage());
			user = null;
		} catch (JSONException e) {
			user = null;
			Log.e("JSONException", e.getMessage());
		}

		Utility.mFacebook = null;
		return user;
	}

	/**
	 * Post image len Facebook
	 * 
	 * @param file
	 *            : URL hoac dia chi patch trong SDcard
	 * @param status
	 *            : status muon viet kem theo anh
	 * @param accessToken
	 *            : Lay trong DB
	 * @return
	 */
	public boolean postToFacebook(String file, String status, String accessToken) {

		Utility.mFacebook = new Facebook(Keys.APP_ID);
		Utility.mFacebook.setAccessToken(accessToken);
		Utility.mFacebook.setAccessExpires(0);

		if (file.startsWith("http") || file.length() == 0) {
			Bundle params = new Bundle();
			params.putString("url", file);
			params.putString("caption", status);

			try {
				String resp = Utility.mFacebook.request("me/photos", params,
						"POST");

				if (resp != null) {
					JSONObject jsonObject = Util.parseJson(resp);
					if (jsonObject != null) {
						Log.d("Upload photo success", jsonObject.toString());
						jsonObject = null;
						return true;
					} else {
						return false;
					}
				} else {
					return false;
				}

			} catch (FileNotFoundException e) {
				Log.e("FileNotFoundException", e.getMessage());
				return false;
			} catch (MalformedURLException e) {
				Log.e("MalformedURLException", e.getMessage());
				return false;
			} catch (IOException e) {
				Log.e("IOException", e.getMessage());
				return false;
			} catch (JSONException e) {
				Log.e("JSONException", e.getMessage());
				return false;
			} catch (FacebookError e) {
				Log.e("FacebookError", e.getMessage());
				return false;
			}
		} else {
			File f = new File(file);
			Uri photoUri = Uri.fromFile(f);
			if (photoUri != null) {
				Bundle par = new Bundle();
				try {
					par.putByteArray("photo",
							Utility.scaleImage(mContext, photoUri));
				} catch (IOException e) {
					Log.e("IOException", e.getMessage());
					return false;
				}
				par.putString("caption", status);

				try {
					String resp = Utility.mFacebook.request("me/photos", par,
							"POST");

					if (resp != null) {
						JSONObject jsonObject = Util.parseJson(resp);
						if (jsonObject != null) {
							Log.d("Upload photo success", jsonObject.toString());
							jsonObject = null;
							return true;
						} else {
							return false;
						}
					} else {
						return false;
					}

				} catch (FileNotFoundException e) {
					Log.e("FileNotFoundException", e.getMessage());
					return false;
				} catch (MalformedURLException e) {
					Log.e("MalformedURLException", e.getMessage());
					return false;
				} catch (IOException e) {
					Log.e("IOException", e.getMessage());
					return false;
				} catch (JSONException e) {
					Log.e("JSONException", e.getMessage());
					return false;
				} catch (FacebookError e) {
					Log.e("FacebookError", e.getMessage());
					return false;
				}
			} // end if

			f = null;
			photoUri = null;
		}

		Utility.mFacebook = null;
		return false;
	}

	/**
	 * Check ins image len Facebook
	 * 
	 * @param file
	 *            : URL hoac dia chi patch trong SDcard
	 * @param status
	 *            : status muon viet kem theo anh
	 * @param accessToken
	 *            : Lay trong DB
	 * @param place
	 *            : Place
	 * @return
	 */
	public boolean checkInToFacebook(String file, String status,
			String accessToken, Place place, String listFriendID, String url_id) {
		boolean result = false;
		Utility.mFacebook = new Facebook(Keys.APP_ID);
		Utility.mFacebook.setAccessToken(accessToken);
		Utility.mFacebook.setAccessExpires(0);

		Bundle params = new Bundle();
		params.putString("message", status);
		params.putString("place", place.getIdPlace());
		params.putString("coordinates",
				"{\"latitude\":\"" + place.getLatitude()
						+ "\",\"longitude\":\"" + place.getLongitude() + "\"}");
		params.putString("tags", listFriendID);
		params.putString("link", Constant.WEB_ROOT + url_id);
		params.putString("picture", file);
		try {
			String resp = Utility.mFacebook.request("me/checkins", params,
					"POST");

			if (resp != null) {
				JSONObject jsonObject = Util.parseJson(resp);
				if (jsonObject != null) {
					Log.d("Upload photo success", jsonObject.toString());
					jsonObject = null;
					result = true;
				} else {
					result = false;
				}
			} else {
				result = false;
			}
		} catch (MalformedURLException e) {
			Log.e("MalformedURLException", e.getMessage());
			result = false;
		} catch (IOException e) {
			Log.e("IOException", e.getMessage());
			result = false;
		} catch (JSONException e) {
			Log.e("JSONException", e.getMessage());
			result = false;
		} catch (FacebookError e) {
			Log.e("FacebookError", e.getMessage());
			result = false;
		}

		Utility.mFacebook = null;
		return result;
	}

	/**
	 * Lay thong tin cac dia diem xung quanh Dia diem goc
	 * 
	 * @param accessTokenFB
	 *            : lay trong DB
	 * @param lat
	 *            : Lat cua user
	 * @param lon
	 *            : Lon cua user
	 * @return
	 */
	public ArrayList<Place> getLocationFB(String accessTokenFB, String lat,
			String lon, String query) {
		ArrayList<Place> result = new ArrayList<Place>();
		Utility.mFacebook = new Facebook(Keys.APP_ID);
		Utility.mFacebook.setAccessToken(accessTokenFB);
		Utility.mFacebook.setAccessExpires(0);

		if (lat != null && lon != null && lat.length() > 0 && lon.length() > 0) {
			Bundle params = new Bundle();
			if (!query.equals("")) {
				params.putString("q", query);
			}
			params.putString("type", "place");
			params.putString("center", lat + "," + lon);
			params.putString("distance", "2000");

			try {
				String resp = Utility.mFacebook
						.request("search", params, "GET");
				if (resp != null) {
					Log.d("Facebook-FbAPIs", "Got response: " + resp);
				}
				JsonPaser jP = new JsonPaser();
				result = jP.getPlace(resp);
				jP = null;
			} catch (FileNotFoundException e) {
				result = null;
			} catch (MalformedURLException e) {
				result = null;
			} catch (IOException e) {
				result = null;
			}
		}
		Utility.mFacebook = null;
		return result;
	}

	// FLICKR
	/**
	 * Post to Flickr
	 * 
	 * @param imageUrl
	 *            : Vidu: /mnt/sdcard/temp/SBAD.jpg
	 * @param Title
	 *            : Title cho image muon post. Co the la " "
	 * @param Description
	 *            : Mo ta cho image muon post. Co the la " "
	 * @param token
	 *            : Lay trong DB
	 * @return
	 */
	public boolean postToFlickr(String imageUrl, String Title,
			String Description, String token) {

		String sig_upload = Keys.FLICKR_SECRET_KEY + "api_key"
				+ Keys.FLICKR_APP_ID + "auth_token" + token + "description"
				+ Description + "title" + Title;
		String signature = StringUtil.md5(sig_upload);
		Charset chars = Charset.forName("UTF-8");
		File image = new File(imageUrl);

		try {

			HttpPost httppost = new HttpPost(
					"http://api.flickr.com/services/upload/");
			HttpClient httpclient = new DefaultHttpClient();

			MultipartEntity multipartEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			multipartEntity.addPart("api_key", new StringBody(
					Keys.FLICKR_APP_ID));
			multipartEntity.addPart("auth_token", new StringBody(token));
			multipartEntity.addPart("title", new StringBody(Title, chars));
			multipartEntity.addPart("description", new StringBody(Description));
			multipartEntity.addPart("api_sig", new StringBody(signature));

			multipartEntity.addPart("photo", new FileBody(image));

			httppost.setEntity(multipartEntity);
			HttpResponse response = httpclient.execute(httppost);

			HttpEntity resEntity = response.getEntity();
			String req = EntityUtils.toString(resEntity);
			if (req != null) {
				Log.d("RESPONSE====", req);
			}

			if (req != null && req.contains("<photoid>")
					&& req.contains("</photoid>")) {
				return true;
			}
			return false;
		} catch (Exception e) {
			Log.e("Flickr Exception", e.getLocalizedMessage(), e);
			return false;
		}

	}

	// TUMBLR
	/**
	 * Post photo len TUMBLR
	 * 
	 * @param image
	 *            : dia chi Sdcard
	 * @param caption
	 *            : text mo ta cho image
	 * @param email
	 *            : lay trong DB
	 * @param password
	 *            : lay trong DB
	 * @return
	 */

	public Boolean postToTumblr(String image, String caption, String email,
			String password) {
		Boolean result = false;
		TumblrApi apiTumblr = new TumblrApi(mContext);
		if (image.startsWith("http") || image.length() == 0) {
			result = apiTumblr.postText(Constant.SERVER_NAME, caption + image, email,
					password);
		} else {
			result = apiTumblr.postImage(image, caption, email, password);
		}
		return result;
	}

	// WEIBO
	/**
	 * Post image + status len blog weibo.
	 * 
	 * @exception : post false khi 2 lan post lien tiep co gia tri giong nhau.
	 *            Yeu cau test phai gia tri khac nhau. Hoac ko quan tam toi ket
	 *            qua post dc hay ko
	 * @param file
	 *            : URL hoac dia chi luu tai SDcard
	 * @param status
	 *            : Status post len blog weibo
	 * @param longitude
	 *            : Lay theo photoDetail hoac Co the de gia tri " "
	 * @param latitude
	 *            : Lay theo photoDetail hoac Co the de gia tri " "
	 * @param token
	 *            : Lay trong DB
	 * @param tokenSecret
	 *            : Lay trong DB
	 * @return
	 * @throws WeiboException
	 */
	public boolean postToWeibo(String file, String status, String longitude,
			String latitude, String token, String tokenSecret) {

		Weibo weibo = Weibo.getInstance();
		weibo.setupConsumerConfig(Keys.WEIBO_CONSUMER_KEY,
				Keys.WEIBO_CONSUMER_SECRET);
		AccessTokenWeibo mWeiboAccessToken = new AccessTokenWeibo(token,
				tokenSecret);
		weibo.setAccessToken(mWeiboAccessToken);

		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", Keys.WEIBO_CONSUMER_KEY);
		if (file.startsWith("http://") || file.length() == 0) {
			String imageUrl = file;
			status = status + " " + imageUrl;
			bundle.add("status", status);
		} else {
			bundle.add("pic", file);
			bundle.add("status", status);
		}
		if (!TextUtils.isEmpty(longitude)) {
			bundle.add("lon", longitude);
		}
		if (!TextUtils.isEmpty(latitude)) {
			bundle.add("lat", latitude);
		}

		String url = "";
		if (file.startsWith("http://") || file.length() == 0) {
			url = Weibo.SERVER + "statuses/update.json";
		} else {
			url = Weibo.SERVER + "statuses/upload.json";
		}
		AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);

		if (weiboRunner.request(mContext, url, bundle, Utility.HTTPMETHOD_POST) == true) {
			weibo = null;
			weiboRunner = null;
			return true;
		} else {
			weibo = null;
			weiboRunner = null;
			return false;
		}
	}

	/**
	 * *************************************************************************
	 * ******************** Cac method khac
	 */
	/**
	 * InputStream to String
	 * 
	 * @param is
	 *            InputStream
	 * @return String
	 * @throws IOException
	 */
	private String inputStreem2str(InputStream is) throws IOException {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is,
				"UTF-8"));
		StringBuffer buf = new StringBuffer();
		String str;
		while (null != (str = reader.readLine())) {
			buf.append(str);
			buf.append("\n");
		}
		return buf.toString();
	}

	private String getJSON(URL url) {
		String result = "";

		try {
			Log.d("FB API Get location", "Get location: " + url);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setRequestMethod("GET");
			http.connect();
			InputStream is = http.getInputStream();
			result = inputStreem2str(is);
			is.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;
	}
}
